const Koa = require("koa");
const KoaRouter = require("@koa/router");
const KoaSession = require("koa-session");

const app = new Koa();

const userRouter = new KoaRouter({ prefix: "/users" });

const session = KoaSession(
  {
    key: "sessionid",
    signed: true, // 是否签名
    maxAge: 24 * 60 * 60 * 1000, // 过期时间
    // httpOnly: true, // 是否只通过http访问
  },
  app
);

app.keys = ["aaa", "bbb", "ccc", "ddd"];
app.use(session);

userRouter.get("/login", (ctx, next) => {
  // 在服务器中为登录的客户端, 设置一个cookie
  ctx.session.user = "allfocuse";

  ctx.body = "登录成功";
});

userRouter.get("/list", (ctx, next) => {
  const value = ctx.session.slogan;
  if (value === "allfocuse") {
    ctx.body = "user list data~";
  } else {
    ctx.body = "请先登录";
  }
});

app.use(userRouter.routes(), userRouter.allowedMethods());

app.listen(8000, () => {
  console.log("服务器启动成功~");
});
